/***
 *
 */
package com.weeego.web.base;

/**
 * 
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;
import com.sql.weeego.bean.base.Log;
import com.weeego.util.file.MakeDir;

/**
 *  写一个简单的Baseaction <br/>
 *  用来处理简单的添加删除修改.<br/>
 * 
 * @author Administrator
 */
public abstract class BaseAction extends ActionSupport {

    protected final Logger logger = Logger.getLogger(getClass());
    protected BaseService service;
    /**
     * 错误的消息
     */
    protected String commondResult;
    // 返回当前要返回的所有的数据
    protected List<Serializable> autolist;
    /**
     * 可以从request中获取,传过来的值.<br/>
     * 当前要显示的页数
     */
    protected int nowpage;
    /**
     * 一页显示的数据行数
     */
    protected int pagesize;
    /**
     * 用来临时保存id的.<br/>
     * 读取,删除的时候用<br/>
     */
    protected int id;
    /**
     * 读取列表,分页的时候用来传递hql
     */
    protected String hql;

    // 操作的状态
    /***************************************************************************
     * 1、 2、 3、 4、 5、
     *操作的状态<br/>
     * 1 保存,修改<br/>
     * 2 返回所有的记录<br/>
     * 3 查找 分页<br/>
     * 4 读取单挑记录<br/>
     * 5 ,6 重复都是读取单条记录<br/>
     * 其他 空方法,返回到session<br/>
     **************************************************************************/
    private int act;
    /**
     * 分页的对象<br/>
     * 再分页得时候返回这个对象,用来传值
     */
    protected Page page;

    /**
     * 获取当前分页
     * @return
     */
    public int getNowpage() {
        if (nowpage < 1) {
            nowpage = 1;
        }
        return nowpage;
    }

    /**
     * 执行对应的操作,添加.删除.修改.显示.分页等等
     * @return
     */
    public String action() {
        if (act == 1) {
            return "add" + save();
        } else if (act == 2) {
            autolist = findByHql(getHql());
            return "list" + SUCCESS;
        } else if (act == 3) {
            page = findPage(getHql(), getNowpage(), getPagesize());
            return "page" + SUCCESS;
        } else if (act == 4) {
            // 用于复制
            objectForm = getService().findObjectById(objectForm, id);
            logger.info(objectForm);
            return "read" + SUCCESS;
        } else if (act == 5) {
            // 用于编辑
            objectForm = getService().findObjectById(objectForm, id);
            logger.info(objectForm);
            return "read" + SUCCESS;
        } else if (act == 6) {
            // 用于展示
            objectForm = getService().findObjectById(objectForm, id);
            logger.info(objectForm);
            return "read" + SUCCESS;
        } else if (act == 7) {
            // 用于删除
            getService().deleteById(objectForm, id);
            logger.info(objectForm);
            return "del" + SUCCESS;
        } else {

            return SUCCESS;
        }
    }

    /**
     * 默认值执行这个方法<br/>
     * 这里自动调用action
     * @return
     * @throws java.lang.Exception
     */
    public String execute() throws Exception {
        String opInfo = action();
        if (commondResult != null) {
        }
        return opInfo;
    }

    /**
     * 获取当前的错误消息
     * @return
     */
    public String getCommondResult() {
        return commondResult;
    }

    /**
     * 设置错误消息
     * @param commondResult
     */
    public void setCommondResult(String commondResult) {
        this.commondResult = commondResult;
    }
    /**
     * 页面对象，用来传值的
     *
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    protected Serializable objectForm;

    /**
     * 页面上要用这个名字来命名form中的各个input<br/>
     * struts2会自动封装到对象里面
     * @return
     */
    public Serializable getObjectForm() {
        return objectForm;
    }

    /**
     * 设置objectForm
     * @param objectForm
     */
    public void setObjectForm(Serializable objectForm) {
        this.objectForm = objectForm;
    }

    /**
     * 保存&修改的方法
     *
     * @return
     */
    public String save() {
        try {
            service.saveOrUpdate(objectForm);
            //savelog("save the objectForm . the object" + " value is :" + objectForm);
            return "success";
        } catch (Exception ex) {
            return ERROR;
        }
    }

    /***************************************************************************
     *
     * @param osavebject
     * @return
     */
    public String saveit(Serializable osavebject) {
        try {
            service.save(osavebject);
            savelog("save the othere object ,the object value is :" + objectForm);
            return "success";
        } catch (Exception ex) {
            return ERROR;
        }
    }

    public String readoneByObject(int id) {
        try {
            objectForm = service.findObjectById(objectForm, id);
            return SUCCESS;
        } catch (Exception ex) {
            return ERROR;
        }
    }

    public String readoneById(int id) {
        try {
            objectForm = service.findObjectById(objectForm, id);
            return SUCCESS;
        } catch (Exception ex) {
            return ERROR;
        }
    }

    public String readoneById(Object id) {
        try {
            objectForm = service.findObjectById(objectForm, (String) id);
            return SUCCESS;
        } catch (Exception ex) {
            return ERROR;
        }
    }

    /**
     * 删除的方法
     *
     * @return
     */
    public String del() {
        if (objectForm != null) {
            service.delete(objectForm);
            savelog("del the othere object ,the object value is :" + objectForm);
            return "success";
        } else {
            return "error";
        }
    }

    public String delById(int i) {
        if (objectForm != null) {
            service.deleteById(objectForm, i);
            savelog("del the othere object ,the object id is :" + i);
            return "success";
        } else {
            return ERROR;
        }
    }

    public String delByIds(String id) {
        if (objectForm != null) {
            service.deleteById(objectForm, id);
            savelog("del the othere object ,the object id is :" + id);
            return "success";
        } else {
            return ERROR;
        }
    }

    /***************************************************************************
     * 为dwr写的方法删除
     *
     * @return
     **************************************************************************/
    public void dwr_del(String id) {
        delByIds(id);
    }

    /***************************************************************************
     *
     * @return
     **************************************************************************/
    public Serializable getEtaoobject() {
        return objectForm;
    }

    public void setEtaoobject(Serializable objectForm) {
        this.objectForm = objectForm;
    }

    @SuppressWarnings("unchecked")
    public List findByHql(String hql) {
        return service.findByHql(hql);
    }

    public List findPageList(String hql, int nowpage1, int pagesize) {

        if ("".equals(hql)) {
            return null;
        } else {
            if (nowpage1 >= 1) {
                return service.findByHql(nowpage1, pagesize, hql);
            } else {
                return findByHql(hql);
            }
        }

    }

    public Page findPage(String hql, int nowpage, int pagesize) {

        Page _Page = new Page(nowpage, service.countByHql(" select count( t ) " + hql), pagesize,
                findPageList(hql, nowpage, pagesize));

      //  logger.info(" select count( t ) " + hql + "-----------------------------------------!" + service.countByHql(" select count( t ) " + hql));


        return _Page;

    }

    /***************************************************************************
     * 这里完成，公用的保存，删除，修改，以及列表的方法
     **************************************************************************/
    /***************************************************************************
     * 以下是用来生成静态页面调用的方法！
     **************************************************************************/
    /**
     * 读取一个url的内容，并返回字符串。
     *
     * @param htmlurl
     * @return
     * @throws IOException
     */
    public String getOneHtml(String htmlurl, String bianma) throws IOException {
        URL url;
        String temp;
        final StringBuffer sb = new StringBuffer();
        try {
            url = new URL(htmlurl);
            final BufferedReader in = new BufferedReader(new InputStreamReader(
                    url.openStream(), bianma));
            while ((temp = in.readLine()) != null) {
                sb.append(temp);
            }
            in.close();
        } catch (final MalformedURLException me) {
            // System.out.println("the url is error");
            me.getMessage();
            throw me;
        } catch (final IOException e) {
            e.printStackTrace();
            throw e;
        }
        return sb.toString();
    }

    /**
     * 读取一个url的内容，并返回字符串。
     *
     * @param htmlurl
     * @return
     * @throws IOException
     */
    public String getOneHtml(String htmlurl) throws IOException {
        URL url;
        String temp;
        final StringBuffer sb = new StringBuffer();
        try {
            url = new URL(htmlurl);
            final BufferedReader in = new BufferedReader(new InputStreamReader(
                    url.openStream(), "UTF-8"));
            while ((temp = in.readLine()) != null) {
                sb.append(temp);
            }
            in.close();
        } catch (final MalformedURLException me) {
            // System.out.println("the url is error");
            me.getMessage();
            throw me;
        } catch (final IOException e) {
            e.printStackTrace();
            throw e;
        }
        return sb.toString();
    }

    /***************************************************************************
     * 保存文件
     *
     * @param filename
     * @param currPath
     * @param filecontent
     * @return
     **************************************************************************/
    public String saveString(String filename, String path, String filecontent,
            String coding) {

        MakeDir _MakeDir = new MakeDir();
        _MakeDir.makeDir(path);
        logger.info(path);
        try {
            FileOutputStream fos = new FileOutputStream(path + File.separator + filename);
            Writer out = new OutputStreamWriter(fos, coding);
            out.write(filecontent);
            out.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";

    }

    /***************************************************************************
     * 保存文件
     *
     * @param filename
     * @param currPath
     * @param filecontent
     * @return
     **************************************************************************/
    public String saveString(String filename, String path, String filecontent) {

        MakeDir _MakeDir = new MakeDir();
        _MakeDir.makeDir(path);
        logger.info(path);
        try {
            FileOutputStream fos = new FileOutputStream(path + File.separator + filename);
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.write(filecontent);
            out.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";

    }

    /***************************************************************************
     * 以上是用来生成静态页面调用的方法！
     **************************************************************************/
    public BaseService getService() {
        return service;
    }

    public void setService(BaseService service) {
        this.service = service;
    }

    public Logger getLogger() {
        return logger;
    }

    public void savelog(String dowhat) {

        Log _Log = new Log();
        logger.info("Date===============" + MyDate.getNowDate());

        _Log.setAddtime(MyDate.getNowDate());
        _Log.setLog(dowhat);
        _Log.setTitle(objectForm.getClass().getName());
        service.save(_Log);

    }

    public void setNowpage(int nowpage) {
        this.nowpage = nowpage;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    public List<Serializable> getAutolist() {
        return autolist;
    }

    public void setAutolist(List<Serializable> autolist) {
        this.autolist = autolist;
    }

    public int getPagesize() {

        if (pagesize < 1) {
            // 默认15条
            pagesize = 15;
        }

        return pagesize;
    }

    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }

    public int getAct() {
        return act;
    }

    public void setAct(int act) {
        this.act = act;
    }

    public String getHql() {
        if ("".equals(hql) || hql == "" || hql == null) {
            logger.info("do this");
            hql = "  from " + objectForm.getClass().getName() + " t order by t.id desc";
        }
        return hql;
    }

    public void setHql(String hql) {
        this.hql = hql;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
